package cn.wolfcode.shiro;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.EmployeeMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MyCrmRealm extends AuthorizingRealm {
    @Autowired
    private EmployeeMapper employeeMapper;

    //提供认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //通过token获取用户名（用户登录的时候填的）
        Object username = token.getPrincipal();
        //判断是否存在数据库（根据名字查询员工）
        Employee employee = employeeMapper.selectByUsername((String) username);
        if(employee!=null){
            //身份对象，真正的密码，当前realm的名字
            return new SimpleAuthenticationInfo(employee,employee.getPassword(),
                    this.getName());
        }
        //返回值就是查询出来的数据，如果查到这个账号，就应该返回该账号正确的数据，如果查不到，就返回null
        return null;
    }
    //提供授权信息
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        SimpleAuthorizationInfo info =new SimpleAuthorizationInfo();

        // 将用户拥有的角色添加到授权信息对象中，供 Shiro 权限校验时使用
        info.addRoles(Arrays.asList("seller"));
        // 根据登录用户的 id 查询到其拥有的所有权限表达式
        List<String> expressions = Arrays.asList("employee:list","employee:save");
        // 将用户拥有的权限添加到授权信息对象中，供 Shiro 权限校验时使用
        info.addStringPermissions(expressions);
        return info;
    }
}
